package com.lvyq.javaprint.controller;

import cn.hutool.setting.Setting;
import com.lvyq.javaprint.model.ProxySettingModel;
import com.lvyq.javaprint.util.SettingUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description  代理转发+响应本地静态资源
 * @author lvyq
 * @param[1] null
 * @throws

 * @time 2024-08-09 17:20
 */
@Controller
public class ProxyController {


    private final RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.PATCH})
    @ResponseBody
    public ResponseEntity<byte[]> proxy(HttpMethod method,
                                        @RequestHeader MultiValueMap<String, String> headers,
                                        @RequestBody(required = false) byte[] body,
                                        HttpServletRequest request) {
        ProxySettingModel proxySettingModel = SettingUtils.readProxySetting();
        String targetUrl="";
        //使用代理
        if (proxySettingModel.getType().equals("2")){
            targetUrl="http://"+proxySettingModel.getDomain()+":"+proxySettingModel.getPort()+"/";
        }
        String proxyUrl = targetUrl + request.getRequestURI();
        //全局忽略浏览器的默认访问网站图标的行为
        if ("/favicon.ico".equals(request.getRequestURI())) {
            return ResponseEntity.ok().build();
        }
        System.out.println("proxyUrl = " + proxyUrl);
        HttpEntity<byte[]> entity = new HttpEntity<>(body, headers);
        ResponseEntity<byte[]> response = restTemplate.exchange(proxyUrl, method, entity, byte[].class);
        return ResponseEntity
                .status(response.getStatusCode())
                .headers(response.getHeaders())
                .body(response.getBody());
    }


    /**
     * @description 委托模版资源
     * @author lvyq
     * @param[1] filename
     * @throws
     * @return String
     * @time 2024-08-13 10:54
     */
    @GetMapping("/powerAttorney/{filename}")
    @ResponseBody
    public String readFile(@PathVariable("filename") String filename) throws IOException {
       // ClassPathResource resource = new ClassPathResource("public/powerAttorney/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/powerAttorney/" +filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }

    /**
     * @description 报告模版资源
     * @author lvyq
     * @param[1] filename
     * @throws
     * @return String
     * @time 2024-08-14 9:25
     */
    @GetMapping("/report/{filename}")
    @ResponseBody
    public String readReport(@PathVariable("filename") String filename) throws IOException {

       // ClassPathResource resource = new ClassPathResource("public/report/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/report/" + filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }


    @GetMapping("/originalRecords/{filename}")
    @ResponseBody
    public String readOriginalRecords(@PathVariable("filename") String filename) throws IOException {

      //  ClassPathResource resource = new ClassPathResource("public/originalRecords/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/originalRecords/" +filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }


    //不合格报告打印
    @GetMapping("/public/unquaLedger/{filename}")
    @ResponseBody
    public String unquaLedger(@PathVariable("filename") String filename) throws IOException {

        //  ClassPathResource resource = new ClassPathResource("public/originalRecords/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/unquaLedger/" +filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }


    /**
     * @description 封皮
     * @author lvyq
     * @param[1] filename
     * @throws
     * @return String
     * @time 2024-10-08 11:34
     */
    @GetMapping("/cover/{filename}")
    @ResponseBody
    public String readCover(@PathVariable("filename") String filename) throws IOException {
        //  ClassPathResource resource = new ClassPathResource("public/originalRecords/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/cover/" +filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }

    @GetMapping("/feeList/{filename}")
    @ResponseBody
    public String feeList(@PathVariable("filename") String filename) throws IOException {
        //  ClassPathResource resource = new ClassPathResource("public/originalRecords/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/feeList/" +filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }

    @GetMapping("/fonts/{filename}")
    public ResponseEntity<Object> getFile(@PathVariable("filename")  String filename) {
        HttpHeaders headers = new HttpHeaders();
        if (filename.endsWith("ttf")){
            byte[] fileContent = new byte[0];
            try {
                fileContent = getInputStream("public/fonts/" +filename).readAllBytes();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
          //  headers.setContentType(MediaType.valueOf("font/ttf"));
            headers.setContentType(MediaType.valueOf("application/octet-stream"));
            headers.setContentLength(fileContent.length);
            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        }else {
            String reader="{\"path\":\"\",\"descriptors\":[{\"name\":\"微软雅黑\",\"source\":\"../fonts/SimHei.ttf\"},{\"name\":\"宋体\",\"source\":\"../fonts/song.ttf\"},{\"name\":\"黑体\",\"source\":\"../fonts/SimHei.ttf\"}]}";
            return new ResponseEntity<>(reader, headers, HttpStatus.OK);

        }
    }

    /**
     * @description 获取流
     * @author lvyq
     * @param[1] path
     * @throws
     * @return InputStream
     * @time 2024-08-15 14:19
     */
   public InputStream getInputStream(String path) throws FileNotFoundException {
       String property = System.getProperty("user.dir");
       property=property+"\\"+path;
       System.out.println("property = " + property);
       File file = new File(property);
       InputStream inputStream= new FileInputStream(file);
       return inputStream;
   }

    public static void main(String[] args) {
        try {
            test01();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  static void test01() throws DocumentException, IOException {
        String property = System.getProperty("user.dir");
        String filePath=property+"\\setting.xml";
        // 读取xml文件
        Document doc=new SAXReader().read(new File(filePath));
        // 获取根节点
        Element rootElement = doc.getRootElement();

        // 获取代理设置
        Element proxyElem= rootElement.element("proxy");
        Element content = proxyElem.element("content");
        //当前节点的所有属性
        List<Attribute> listAttr=content.attributes();
        String name1 = content.attribute("name").getValue();
        for(Attribute attr:listAttr){
            //属性名称
            String name=attr.getName();
            //属性的值
            String value=attr.getValue();
            System.out.println("属性名称："+name+"属性值："+value);
            if (name.equals("value")) {
                attr.setValue("2");
            }
        }

        // 将结果保存
        FileOutputStream out =new FileOutputStream(filePath);
        OutputFormat format= OutputFormat.createPrettyPrint();
        XMLWriter writer=new XMLWriter(out,format);
        writer.write(doc);
        writer.close();
    }

}
